import Web3 from "web3";
import {useEffect} from "react";
import tokenJson from "../build/KerwinToken.json"
import exchangeJson from "../build/Exchange.json"
import Balance from "./Balance";
import Order from "./Order";
import {loadBalanceData} from "../redux/slices/balanceSlice";
import {useDispatch} from "react-redux";
import {loadCancelOrderData,loadAllOrderData,loadFillOrderData} from "../redux/slices/orderSlice";
export default function Content(){
    const dispatch = useDispatch();
    useEffect(() => {
        async function  start(){
            //1.获取连接后的合约
            const web = await initWeb()
            // console.log(web)
            window.web = web
            //2.获取资产信息
            dispatch(loadBalanceData(web))
            //3.获取订单信息
            dispatch(loadCancelOrderData(web))
            dispatch(loadAllOrderData(web))
            dispatch(loadFillOrderData(web))
            //4.监听
            web.exchange.events.Order({},(error,event)=>{
                dispatch(loadAllOrderData(web))
            })
            web.exchange.events.Cancel({},(error,event)=>{

                dispatch(loadCancelOrderData(web))
            })
            web.exchange.events.Trade({},(error,event)=>{
                dispatch(loadFillOrderData(web))
                dispatch(loadBalanceData(web))
            })

        }
        start()
    }, [dispatch]);
    async function initWeb(){
        const web3 = new Web3(Web3.givenProvider || "http://localhost:8545");
        let accounts = await web3.eth.requestAccounts()
        // console.log(tokenJson)

        const netWorkId = await web3.eth.net.getId();//公链地址
        //获取KerwinToken
        const tokenAbi = tokenJson.abi;
        const tokenAddress = tokenJson.networks[netWorkId].address;//
        const token = await new web3.eth.Contract(tokenAbi,tokenAddress)
        //获取Exchange
        const exchangeAbi = exchangeJson.abi;
        const exchangeAddress = exchangeJson.networks[netWorkId].address;
        const exchange = await new web3.eth.Contract(exchangeAbi,exchangeAddress)
        // console.log(exchange)
        return{
            web3,
            account:accounts[0],
            token,
            exchange
        }
    }
    return (
        <div>
            <Balance/>
            <Order/>
        </div>
    )
}